package edu.jamestang.yeb.controller;

import edu.jamestang.yeb.entity.Admin;
import edu.jamestang.yeb.service.AdminService;
import edu.jamestang.yeb.util.MinioUtil;
import edu.jamestang.yeb.util.Resp;
import io.minio.MinioClient;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

/**
 * @author JamesTang
 * @date 2021/12/29 19:20
 */
@Slf4j
@RestController
public class AdminInfoController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private MinioUtil minioUtil;

    @ApiOperation(value = "Update current user info")
    @PutMapping("/admin/info")
    public Resp updateAdmin(@RequestBody Admin admin, Authentication authentication){
        if(adminService.updateById(admin)){

            SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(admin, null, authentication.getAuthorities()));
            return Resp.success("Update successful");
        }
        return Resp.error("Update failure");
    }

    @ApiOperation(value = "Update user password")
    @PutMapping("/admin/pass")
    public Resp updateAdminPassword(@RequestBody Map<String, Object> info){

        String oldPass = (String) info.get("oldPass");
        String pass = (String) info.get("pass");
        Integer adminId = (Integer) info.get("adminId");
        return adminService.updateAdminPassword(oldPass,pass,adminId);
    }

    @ApiOperation(value = "Update user icon")
    @PostMapping("/admin/userface")
    public Resp updateAdminUserFace(MultipartFile file, Integer id, Authentication authentication) throws Exception {

        minioUtil.uploadFile("yeb", file.getOriginalFilename(), file);


        return adminService.updateAdminUserFace(file, id, authentication);
    }
}
